package com.ifp.opengate.boot.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * Created by mogs on 2019/4/19.
 */
public final class RequestUtil {
    public static String getHeaderValue(ServerHttpRequest request, String key) {
        if (request.getHeaders().containsKey(key)) {
            return request.getHeaders().getFirst(key);
        }
        return null;
    }

    public static String getParamValue(ServerHttpRequest request, String key) {
        if (request.getQueryParams().containsKey(key)) {
            return request.getQueryParams().getFirst(key);
        }
        return null;
    }

    /**
     * 获取请求的ActionId
     * 
     * @param request
     * @return
     */
    public static String getActionId(ServerHttpRequest request) {
        String contextPath = "/open-gate";
        String reqStr = request.getPath().pathWithinApplication().value();
        if (reqStr.contains(contextPath)) {
            reqStr = reqStr.substring(reqStr.indexOf(contextPath) + contextPath.length());
        }
        int idx = reqStr.lastIndexOf(".");

        if (idx != -1) {
            reqStr = reqStr.substring(0, idx);
        }

        return reqStr;
    }

    /**
     * 判断时间是否在 [startTime,endTime] 区间
     * 
     * @param startTime
     * @param endTime
     * @param currentTime
     * @return
     */
    public static boolean checkValidTime(String startTime, String endTime, String currentTime) {
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
        Calendar cd_startTime = Calendar.getInstance();
        Calendar cd_endTime = Calendar.getInstance();
        Calendar cd_currentTime = Calendar.getInstance();
        try {
            cd_startTime.setTime(df.parse(startTime));
            cd_endTime.setTime(df.parse(endTime));
            cd_currentTime.setTime(df.parse(currentTime));
            if (cd_currentTime.compareTo(cd_startTime) >= 0 && cd_currentTime.compareTo(cd_endTime) <= 0) {
                return true;
            }

        } catch (ParseException e) {
            return false;
        }
        return false;
    }
}
